﻿using Rebex.Security.Cryptography;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using CS_AES_CTR;
using CCode;

namespace BamiTech.AirServer
{
    public class AirPlayServer
    {
        public static void ClampPrivateKeyInline(byte[] key)
        {
            if (key == null) throw new ArgumentNullException("key");
            if (key.Length != 32) throw new ArgumentException(String.Format("key must be 32 bytes long (but was {0} bytes long)", key.Length));

            key[31] &= 0x7F;
            key[31] |= 0x40;
            key[0] &= 0xF8;
        }

        private void create_ed_key(AirPairInfo airPairInfo)
        {
            byte[] private_key = new byte[64] { 8, 221, 114, 96, 124, 107, 2, 199, 198, 154, 211, 161, 17, 247, 88, 255, 143, 122, 130, 11, 15, 56, 119, 116, 112, 1, 174, 249, 235, 135, 168, 212, 138, 69, 250, 203, 218, 252, 72, 5, 249, 120, 116, 29, 243, 212, 239, 168, 51, 71, 122, 85, 18, 212, 162, 208, 80, 124, 72, 107, 154, 127, 38, 133 };
            byte[] public_key = new byte[32] { 138, 69, 250, 203, 218, 252, 72, 5, 249, 120, 116, 29, 243, 212, 239, 168, 51, 71, 122, 85, 18, 212, 162, 208, 80, 124, 72, 107, 154, 127, 38, 133 };
            Array.Copy(public_key, airPairInfo.ed_pub, 32);
            Array.Copy(private_key, airPairInfo.ed_pri, 64);

        }

        private void test()
        {
            Fairplay fairPlay = new Fairplay();
            byte[] body = new byte[16];
            byte[] output = null;
            fairPlay.setup(body, out output);
        }

        public void StartServer()
        {
            test();
            var server = new AirPlayServer_version2();
            server.Start();
            server.messageSent += Server_messageSent;
            server.clientConnected += Server_clientConnected;
            server.authorisationRequest += Server_authorisationRequest;
            server.playbackEvent += Server_playbackEvent;
            server.playURL += Server_playURL;
            server.playImage += Server_playImage;

            var apr = new AirPlayServer_mdns("My AirPlay Device");
            apr.StartMdnsAsync();
        }

        private void Server_playImage(object sender, object theImage)
        {
        }

        private void Server_playURL(object sender, string url, double position)
        {
            Debug.WriteLine($"Server_playURL:{url}");
        }

        private void Server_playbackEvent(object sender, string action, string param = "")
        {
        }

        private void Server_authorisationRequest()
        {
        }

        private void Server_clientConnected(object sender, string message)
        {
            Debug.WriteLine($"Server_clientConnected");
        }

        private void Server_messageSent(object sender, string message)
        {
            Debug.WriteLine($"Server_messageSent");
        }
    }
}
